package com.hyh.sso.service.impl;

import com.alibaba.fastjson.JSON;
import com.hyh.sso.LoginStatus;
import com.hyh.sso.po.LoginResult;
import com.hyh.sso.po.LoginUser;
import com.hyh.sso.service.LoginService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

/**
 * 登录接口实现
 *
 * @Author: heyuhua
 * @Date: 2021/1/8 17:56
 */
@Service
public class LoginServiceImpl implements LoginService {

    private static final Logger LOG = LoggerFactory.getLogger(LoginServiceImpl.class);

    /**
     * rest接口请求模板
     */
    private static RestTemplate restTemplate = new RestTemplate();


    @Override
    public LoginResult login(String account, String password, String callbackUrl) {
        LoginResult loginResult = null;
        try {
            HttpHeaders headers = new HttpHeaders();
            //设置请求媒体数据类型
            headers.setContentType(MediaType.APPLICATION_JSON);
            //设置返回媒体数据类型
            headers.add("Accept", MediaType.APPLICATION_JSON.toString());
            HttpEntity<String> formEntity = new HttpEntity<String>(JSON.toJSONString(new LoginUser(account, password)), headers);
            loginResult = restTemplate.postForObject(callbackUrl, formEntity, LoginResult.class);
        } catch (Exception e) {
            LOG.error("login valid callback error", e);
            return new LoginResult(LoginStatus.CALLBACK_ERROR);
        }
        return loginResult == null ? new LoginResult(LoginStatus.ERROR) : loginResult;
    }


}
